package com.skyhigh.web.webservice.controllers;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import com.skyhigh.web.webservice.domain.Usuario;
import com.skyhigh.web.webservice.services.UsuarioService;
import com.skyhigh.web.webservice.validators.LoginValidator;

@Controller
public class LoginController {
	
	@Autowired
	private UsuarioService usuarioService;		
	protected final Log logger = LogFactory.getLog(getClass());	
	LoginValidator loginValidator;
	
	 
	@Autowired
	public LoginController(LoginValidator loginValidator){
		this.loginValidator = loginValidator;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model){
		Usuario usuario = new Usuario();

		model.addAttribute("usuario", usuario);		
		return "login";
	}
	
		
	@RequestMapping(value="/login.htm", method = RequestMethod.POST)
	public String processSubmit(
		@ModelAttribute("usuario") Usuario entity,
		BindingResult result, SessionStatus status) {				
 
		String now = (new Date()).toString();
        logger.info("Returning Login view with " + now);
        
        
        loginValidator.validate(entity, result);
        
		if (result.hasErrors())
			return "login";
		else {
			if(usuarioService.iniciarSesion(entity)){
				status.setComplete();
				return "desktop";	
			}else
				return "loginFailed";			
		}                                 
	}
	
}
